package com.java.controller;

import com.java.bean.Item;
import com.java.service.ItemService;
import com.java.utils.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private ItemService itemService;
    @Value("${pic.types}")
    private String pictype;

    @RequestMapping(value="/update",method = RequestMethod.POST)
    public String update(Item item,HttpServletRequest request,Model model) throws IOException {
        //1.判断数据修改是，是否传递了新的图片
        MultipartFile picFile=item.getPicFile();
        if(picFile!=null && picFile.getSize() >0){
            UploadPic uploadPic = new UploadPic(request, model, picFile).invoke();
            if (uploadPic.is()) return "item/item_update";
            String pic = uploadPic.getPic();
            item.setPic(pic);
        }
        //2.调用service司改商品信息
        Integer count=itemService.updateById(item);
        if(count==1){
            //跳转展示页面
            return "redirect:/item/list";
        }
        return "redirect:/item/update/"+item.getId();
    }

    //根据id查询商品
    @RequestMapping(value="/update/{id}",method = RequestMethod.GET)
    public String toUpdatePage(@PathVariable Integer id,Model model){
        //1.调用service查询商品信息
        Item item= itemService.findById(id);
        model.addAttribute("item",item);
        //2.转发到修改页面
        return "item/item_update";
    }

    //删除
    @RequestMapping(value="/delete/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public Integer delete(@PathVariable  Integer id){
        Integer count = itemService.deleteById(id);
        return count;
    }

    /**
     * 限制文件的大小，不超过5M
     * 限制文件的类型 jpg png jpeg gif
     * 避免损坏文件
     *
     * @param request
     * @return
     * @throws IOException
     */
    //添加商品
    @RequestMapping("/add")
    public String add(@Valid Item item, BindingResult bindingResult,
                      HttpServletRequest request,Model model) throws IOException {

        if (bindingResult.hasErrors()) {
            //参数不合法
            return "item/item_add";
        }
        //======================图片上传===========================
        MultipartFile picFile = item.getPicFile();
        UploadPic uploadPic = new UploadPic(request, model, picFile).invoke();
        if (uploadPic.is()) return "item/item_add";
        String pic = uploadPic.getPic();
//        ==================================================
        //将封装的pic设置到item中
        item.setPic(pic);
        //调用service保存商品信息
        System.out.println(item);
        Integer count=itemService.save(item);
        if(count==1){
            return "redirect:/item/list";
        }
        model.addAttribute("addInfo","添加商品异常");
        return "item/item_add";
    }

    //商品展示
    @RequestMapping("/list")
    public String list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "size", defaultValue = "5") Integer size,
                       String name,
                       Model model) {
        //1.调用service查询商品信息和分页
        //System.out.println(name);
        PageInfo pageInfo = itemService.findItemByCondition(name, page, size);
        model.addAttribute("pageInfo", pageInfo);
        //2.数据回显将name放入到request域中
        model.addAttribute("name", name);
        return "item/item_list";
    }

    private class UploadPic {
        private boolean myResult;
        private HttpServletRequest request;
        private Model model;
        private MultipartFile picFile;
        private String pic;

        public UploadPic(HttpServletRequest request, Model model, MultipartFile picFile) {
            this.request = request;
            this.model = model;
            this.picFile = picFile;
        }

        boolean is() {
            return myResult;
        }

        public String getPic() {
            return pic;
        }

        public UploadPic invoke() throws IOException {
            //在进行技术传递的时候 生成一个计数器
            boolean flag = false;
            //校验文件类型
            String[] types = pictype.split(",");
            //1.给图片起新名字
            //1.1获取原图片内容
            String fileName = picFile.getOriginalFilename();
            for (String type : types) {
                if (StringUtils.endsWithIgnoreCase(fileName, type)) {
                    //有匹配类型 若是flag值改变则 传递图片正确
                    flag = true;
                    break;
                }
            }
            if (flag == false) {
                //图片类型错误
                model.addAttribute("pinInfo","图片类型错误，要求"+pictype);
                myResult = true;
                return this;
            }
            //校验图片是否损坏 通话读取图片字节流获取图片长宽
            BufferedImage bufferedImage = ImageIO.read(picFile.getInputStream());
            if (bufferedImage == null) {
                //图片损坏
                model.addAttribute("picInfo","图片损坏，请更换图片");
                myResult = true;
                return this;
            }
            //1.2 使用StringUtils获取图片后缀名
            String typeName = StringUtils.substringAfterLast(fileName, ".").toLowerCase();
            //1.3 起新名字
            String prefixName = UUID.randomUUID().toString();
            String newName = prefixName + "." + typeName;
            //2.将图片保存到本地
            File file = new File(request.getRealPath("/") + "static/images/" + newName);
            picFile.transferTo(file);
            //3.封装一个访问路径
            pic = "http://localhost/static/images/" + newName;
            myResult = false;
            return this;
        }
    }
}
